package com.beiding.my.mql.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class StringHide {


    //被隐藏的区块
    private List<Block> blocks = new ArrayList<>();

    private String text;

    private String out;

    private char hideChar = ' ';

    private String result;

    public char getHideChar() {
        return hideChar;
    }

    public void setHideChar(char hideChar) {
        this.hideChar = hideChar;
    }

    public StringHide(String text, String out) {
        this.text = text;
        this.out = out;
    }

    public void hide() {

        int index = 0;
        List<Position> positions = new ArrayList<>();
        while (true) {
            index = text.indexOf(out, index);
            if (index == -1) {
                break;
            } else {
                positions.add(new Position(index));
                index += out.length();
            }
        }

        //根据位置进行一次排序
     //   positions.sort(Comparator.comparingInt(a -> a.getIndex()));

        Stack<Block> pairs = new Stack<>();

        for (Position position : positions) {
            if (pairs.size() == 0) {
                Block block = new Block();
                block.setStart(position.getIndex());
                pairs.push(block);
            } else {
                Block pop = pairs.pop();

                //TODO 区块替换标准
                pop.setEnd(position.getIndex());
                pop.cutText(text);
                blocks.add(pop);
            }
        }

        if (pairs.size() != 0) {
            throw new RuntimeException("不是成对存在:" + text + "  ->  " + out);
        }

        char[] chars = text.toCharArray();

        //对其中的块进行一次隐藏操作
        for (Block block : blocks) {
            for (int i = block.getStart(); i <= block.getEnd(); i++) {
                chars[i] = hideChar;
            }
        }

        result = new String(chars);

    }


    public String getResult() {
        return result;
    }

    public List<Block> getBlocks() {
        return blocks;
    }


    public static void main(String[] args) {

        String s = "dfaoefajofjaeof'aefaefwef'fdasfaef";

        StringHide hide = new StringHide(s, "'");

        hide.hide();

        String result = hide.getResult();

        System.out.println(result);

    }

}
